package com.huawei.rbac.test;

import lombok.SneakyThrows;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class AppleExtends extends Thread {


    private static int num = 50;

    public AppleExtends(String name) {
        super(name);
    }


    @SneakyThrows
    public void run() {
        for (int i = 0; i < 50; i++) {
            Thread.sleep(300);
            synchronized (this) {
                if (num > 0) {
                    System.out.println(super.getName() + "吃了编号为" + num-- + "的苹果");
                }
            }
        }
    }
}


//将lock 和 unlock 之间的代码锁定    吃梨
class Pear implements Runnable {
    private int num = 50;
    private final Lock lock = new ReentrantLock();


    @Override
    public void run() {
        for (int i = 0; i < 50; i++) {
            lock.lock();
            try {
                if (num > 0) {
                    System.out.println(Thread.currentThread().getName() + "吃第" + (num--) + "个梨");
                }
            } finally {
                lock.unlock();
            }

        }

    }
}


class AppleExtendsDemo {

    public static void main(String[] args) {

        new AppleExtends("乔峰").start();
        new AppleExtends("虚竹").start();
        new AppleExtends("段誉").start();
        /*Pear pear = new Pear();
        new Thread(pear, "Thread-1").start();
        new Thread(pear, "Thread-2").start();
        new Thread(pear, "Thread-3").start();*/

    }
}
